package com.zjweu.hkg.Controller;

import com.zjweu.hkg.DAO.UserDAO;
import com.zjweu.hkg.DTO.UserReqest;
import com.zjweu.hkg.DTO.UserUpdateRequest;
import com.zjweu.hkg.POJO.Administrator;
import com.zjweu.hkg.POJO.Result;
import com.zjweu.hkg.POJO.User;
import com.zjweu.hkg.Servies.FileService;
import com.zjweu.hkg.Servies.UserServices;
import com.zjweu.hkg.utils.JwtUtil;
import com.zjweu.hkg.utils.Md5Util;
import org.neo4j.ogm.annotation.RelationshipEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserServices userServices;
    @Autowired
    FileService fileService;
    @Autowired
    private UserDAO userDAO;

    @PostMapping("/register")
    //todo 要用@Pattern来添加校验
    /**
     * 注册接口
     */
    public Result register(@RequestBody  UserReqest userReqest){
        User user=userServices.findUserByName(userReqest.getUserName());
        if(user==null){
            userServices.register(userReqest.getUserName(),userReqest.getUserPsd());
            return Result.success();
        }else{
            return Result.error("用户名已占用！");
        }
    }

    /**
     * 登录接口
     * @param userReqest
     * @return
     */
    @PostMapping("/login")
    public Result<String> login (@RequestBody UserReqest userReqest){
        System.out.println("用户名："+userReqest.getUserName());
        User user=userServices.findUserByName(userReqest.getUserName());
        if(user==null){
            return Result.error("用户不存在");
        }
        if(user.getStatus()!=0){
            return Result.error("用户状态异常！请联系管理员");
        }
        if(user.getAvatarURL()==null||user.getAvatarURL().equals("")){
            user.setAvatarURL("default");
           System.out.println("用户使用了默认头像");
        }
        if(Md5Util.getMD5String(userReqest.getUserPsd()).equals(user.getUserPsd())){
            String token=userServices.createUserToken(user);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    /**
     * 返回所有的用户信息
     * @return
     */
    @PostMapping("/getAllUser")
    public User[] getAllUser(@RequestBody Map<String, Object> requestData){
        int uid= (int)requestData.get("uid");
        Administrator administrator=userServices.findAdminByUserId(uid);
        if(administrator==null){
            System.out.println("用户不是管理员");
            return null;
        }
        User[] users=userServices.getAllUser();
        for (int i = 0; i < users.length; i++) {
            //确保用户密码不返回给前端
            users[i].setUserPsd(null);
        }
        return users;
    }

    /**
     * 根据UID更新用户密码，更新成功返回的是新token
     * @param requestData
     * @return
     */
    @RequestMapping("/updateUserPsdById")
    public Result updateUserPsdById(@RequestBody Map<String, Object> requestData){
        int uid= (int)requestData.get("uid");
        String oldPsd= (String) requestData.get("oldPassword");
        String newPsd= (String) requestData.get("newPassword");
        return userServices.updateUserPsdById(uid,oldPsd,newPsd);
    }
    /**
     * 管理员根据UID修改用户名，不需要返回token
     * @return
     */
    @PostMapping("/adminUpdateUserById")
    public Result<String> adminUpdateUserById(@RequestBody Map<String, Object> requestData){
        int id= (int)requestData.get("id");
        String newUserName= (String) requestData.get("newUserName");
        int status= (int)requestData.get("status");
        //两个user的意思是，如果点击了用户名修改啥也没改，此时user1还未应用更改，则user==user1，否则user!=user1

       User user= userServices.findUserByName(newUserName);
       User user1=userServices.getUserById(id);

       if(user!=null&&user.getId()!=user1.getId()){
           return Result.error("已有重复用户名");
       }
      int update=userServices.updateUserById(id,newUserName,status);
        if(update==1){
            return Result.success("更新成功");
        }else{
            return Result.error("更新失败");
        }
    }
    @PostMapping("/updateUserNameById")
    public Result<String> updateUserNameById(@RequestBody UserUpdateRequest userUpdateRequest){
        User user= userServices.findUserByName(userUpdateRequest.getNewUserName());
        System.out.println(user);
        if(user!=null){
            return Result.error("已有重复用户名");
        }

        int update=userServices.updateUserById(userUpdateRequest.getId(),userUpdateRequest.getNewUserName(),0);
        if(update==1){
            User user1=userServices.getUserById(userUpdateRequest.getId());
            String token=userServices.createUserToken(user1);
            return Result.success(token);
        }else{
            return Result.error("更新失败");
        }
    }

    /**
     * 根据UID删除用户
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/deleteUserById")
    public Result<String> deleteUserById(@RequestBody UserUpdateRequest userUpdateRequest){
        int delete=userServices.deleteUserById(userUpdateRequest.getId());
        if(delete==1){
            return Result.success("删除成功");
        }else{
            return Result.error("删除失败");
        }
    }

    /**
     *
     * 根据UID获取用户
     * @param id
     * @return
     */
    @PostMapping("/getUserById")
    public User getUserById(int id){
        return userServices.getUserById(id);
    }

    /**
     * 将新用户头像发送给minio
     * @param file
     * @param userName
     * @return
     * @throws IOException
     */
    @PostMapping("/updateUserAvatar")
    public ResponseEntity<String> uploadAvatarFile(@RequestParam("file") MultipartFile file,String userName) throws IOException {
        String newFileName= fileService.changeFileNameWithPath(file.getOriginalFilename(),userName,"avatar");
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file.getResource());
        body.add("fileName", newFileName);
        body.add("bucketName", "hkg");

        // 返回响应内容
        return fileService.upload(file,newFileName,body);
    }

    /**
     * 修改完头像后，将头像文件地址存入User表
     * @param requestData
     * @return
     */
    @PostMapping("/updateUserAvatarUrlByUID")
    public Result<String> updateUserAvatarUrlByUID(@RequestBody Map<String, Object> requestData) {
        int uid = (int) requestData.get("uid");
        String url = (String) requestData.get("url");
        return userServices.updateUserAvatarUrlByUID(uid, url);
    }

    /**
     * 更改管理员权限
     * @param requestData
     * @return
     */
    @RequestMapping("/updateAdminPermissionById")
    public Result<String> updateAdminPermission(@RequestBody Map<String, Object> requestData){
        int uid=(int)requestData.get("uid");

        int newPermission= Integer.parseInt((String) requestData.get("newPermission"));
        return userServices.updateAdminPermission(uid,newPermission);
    }

    /**
     * 获取所以管理员
     * @return
     */
    @RequestMapping("/getAllAdmin")
    public List<Administrator> getAllAdmin(@RequestBody Map<String, Object> requestData){
        int uid= (int)requestData.get("uid");
        Administrator administrator=userServices.findAdminByUserId(uid);
        if(administrator==null){
            System.out.println("用户不是管理员");
            return null;
        }
        return userServices.getAllAdmin();
    }

    @RequestMapping("/deleteAdminByAdminId")
    public Result<String> deleteAdminByAdminId(@RequestBody Map<String, Object> requestData){
        int adminId= (int) requestData.get("adminId");
        System.out.println("adminId = " + adminId);
        return userServices.deleteAdminByAdminId(adminId);
    }

    @RequestMapping("/addNewAdminById")
    public Result<String> addNewAdminById(@RequestBody Map<String, Object> requestData){
        int uid;
        try{
           uid=Integer.parseInt((String) requestData.get("uid"));
        }catch (Exception e){
            System.out.println("UID输入错误！");
            return Result.error("UID输入错误！");
        }

        int permission= Integer.parseInt((String) requestData.get("permission"));
        int adminId= (int)requestData.get("adminId");

        Administrator administrator=userServices.findAdminByUserId(adminId);
        if(administrator==null){
            System.out.println("用户不是管理员");
            return null;
        }
        return userServices.addNewAdminById(uid,permission);
    }

    @PostMapping("/follow")
    public Result<String> follow(int followerId,int followedId){

        return userServices.follow(followerId,followedId);
    }
    @PostMapping("/unFollow")
    public Result<String> unFollow(int followerId,int followedId){
        return userServices.unFollow(followerId,followedId);
    }

    @PostMapping("/isFollowing")
    public Result<String> isFollowing(int followerId,int followedId){
        return userServices.isFollow(followerId,followedId);
    }
    @PostMapping("/getFollowedByFollowerId")
    public Result getFollowedByFollowerId(int followerId){
        return userServices.getFollowedByFollowerId(followerId);
    }

    /**
     * 获取已关注的用户，用User对象返回
     * @param followerId
     * @return
     */
    @PostMapping("/getFollowedUserObjByFollowerId")
    public Result getFollowedUserObjByFollowerId(int followerId){
        return userServices.getFollowedUserObjByFollowerId(followerId);
    }
    @PostMapping("/getFollowerByFollowedId")
    public Result getFollowerByFollowedId(int followedId){
        return userServices.getFollowerByFollowedId(followedId);
    }
}
